/*
 * Created on 2006-4-5
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.sitech.portal.system.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import com.sitech.ibnms.core.IPage;
import com.sitech.ibnms.core.JGridBaseAction;
import com.sitech.ibnms.util.RandomGUID;
import com.sitech.portal.system.domain.TblSYS_LOGINMSG;
import com.sitech.portal.system.domain.TblSYS_MODULE;
import com.sitech.portal.system.domain.TblSYS_ROLE_MODULE;
import com.sitech.portal.system.form.ModelForm;
import com.sitech.portal.system.form.ModuleDTO;
import com.sitech.portal.system.service.ISysModuleService;
import com.sitech.portal.system.service.ISysRoleModuleService;
import com.sitech.portal.system.service.ISysSubSystemService;
import com.sitech.portal.system.service.ISysUserModuleLogService;
import com.sitech.portal.util.CommUtil;

/**
 * @author Administrator
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class ModelAction extends JGridBaseAction {
	
	private ISysModuleService sysModuleService;
	private ISysRoleModuleService sysRoleModuleService;
	private ISysSubSystemService sysSubSystemService;
	private ISysUserModuleLogService sysUserModuleLogService;
	private ModelForm theForm = new ModelForm();
	private ModuleDTO[] moduleDTO;
	private String flag;
	private String systemId;
	private List moduleList = new ArrayList();

	public List getModuleList() {
		return moduleList;
	}

	public void setModuleList(List moduleList) {
		this.moduleList = moduleList;
	}

	public ISysModuleService getSysModuleService() {
		return sysModuleService;
	}

	public void setSysModuleService(ISysModuleService sysModuleService) {
		this.sysModuleService = sysModuleService;
	}

	public ISysRoleModuleService getSysRoleModuleService() {
		return sysRoleModuleService;
	}

	public void setSysRoleModuleService(ISysRoleModuleService sysRoleModuleService) {
		this.sysRoleModuleService = sysRoleModuleService;
	}

	public ISysSubSystemService getSysSubSystemService() {
		return sysSubSystemService;
	}

	public void setSysSubSystemService(ISysSubSystemService sysSubSystemService) {
		this.sysSubSystemService = sysSubSystemService;
	}

	public ISysUserModuleLogService getSysUserModuleLogService() {
		return sysUserModuleLogService;
	}

	public void setSysUserModuleLogService(
			ISysUserModuleLogService sysUserModuleLogService) {
		this.sysUserModuleLogService = sysUserModuleLogService;
	}

	public ModelForm getTheForm() {
		return theForm;
	}

	public void setTheForm(ModelForm theForm) {
		this.theForm = theForm;
	}

	public ModuleDTO[] getModuleDTO() {
		return moduleDTO;
	}

	public void setModuleDTO(ModuleDTO[] moduleDTO) {
		this.moduleDTO = moduleDTO;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public String getSystemId() {
		return systemId;
	}

	public void setSystemId(String systemId) {
		this.systemId = systemId;
	}

	public String checkPageNo() {

		flag = "";
		String PAGE_ELEMENT = this.getRequest().getParameter("PAGE_ELEMENT");

		List resultList = sysModuleService.checkPAGE_ELEMENT(PAGE_ELEMENT);

		if (resultList.size() > 0) {
			flag = "1";
		} else {
			flag = "0";
		}

		return SUCCESS;
	}

	/**
	 * 保存角色模块树
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String saveRoleModel() {

		flag = "true";
		try{
			// 得到变量roleId，moduleIds
			String roleId = theForm.getRoleID();
			String mstr = theForm.getModuleIds();
			String[] moduleIds = CommUtil.splitToSS(mstr, "#");
			// 先删除后增加
			sysRoleModuleService.deleteByRoleId(roleId);
	
			TblSYS_ROLE_MODULE obj = new TblSYS_ROLE_MODULE();
			for (int i = 0; i < moduleIds.length; i++) {
				if (!moduleIds[i].equals("")) {
					obj.setROLE_ID(roleId);
					obj.setMODULE_ID(moduleIds[i]);
					sysRoleModuleService.insert(obj);
				}
			}
		}catch(Exception e){
			flag = e.getMessage();
		}

        return  SUCCESS;

	}

	/**
	 * 显示角色模块树
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String mainModulesTree() {

		String roleID = "";
		if (theForm.getRoleID() != null && !theForm.getRoleID().equals("")) {
			roleID = theForm.getRoleID();
		} else {
			roleID = this.getRequest().getParameter("ROLE_ID");
		}

		theForm.setRoleID(roleID);
		List mlst = sysModuleService.findList();
		List rmLst = sysRoleModuleService.findRoleModule();
		TblSYS_ROLE_MODULE[] rmObj = null;
		TblSYS_MODULE[] mObj = null;

		Map map = new HashMap();
		if (rmLst != null && rmLst.size() > 0) {
			rmObj = (TblSYS_ROLE_MODULE[]) rmLst
					.toArray(new TblSYS_ROLE_MODULE[rmLst.size()]);
			for (int i = 0; i < rmObj.length; i++) {
				map.put(String.valueOf(i), rmObj[i].getROLE_ID()
						+ rmObj[i].getMODULE_ID());
				// rmVec.add(rmObj[i].getROLE_ID()+rmObj[i].getMODULE_ID());

			}
		}
		if (mlst != null && mlst.size() > 0) {
			mObj = (TblSYS_MODULE[]) mlst
					.toArray(new TblSYS_MODULE[mlst.size()]);
			moduleDTO = new ModuleDTO[mObj.length];
			for (int i = 0; i < mObj.length; i++) {
				moduleDTO[i] = new ModuleDTO();
				moduleDTO[i].setLevel(getTypeLevel(mObj[i].getMODULE_ID()));
				moduleDTO[i].setMId(mObj[i].getMODULE_ID());
				moduleDTO[i].setMName(mObj[i].getMODULE_NAME());
				moduleDTO[i].setStrChecked("false");

				for (int j = 0; j < map.size(); j++) {
					if (((String) map.get(String.valueOf(j))).equals(roleID
							+ mObj[i].getMODULE_ID())) {
						moduleDTO[i].setStrChecked("true");
						break;
					}
				}
			}
		}

		return SUCCESS;
	}
        
        /**
         * 新版Module树
         * @param mapping
         * @param form
         * @param request
         * @param response
         * @return
         * @throws BaseException 
         */
        public String newModulesTree() {
                String roleID = "";
                if (theForm.getRoleID() != null && !theForm.getRoleID().equals("")) {
                    roleID = theForm.getRoleID();
                } else {
                    roleID = this.getRequest().getParameter("ROLE_ID");
                }
                theForm.setRoleID(roleID);
                return SUCCESS;
        }
        
        public String newModulesTreeJSON() {
            String ROLE_ID = this.getRequest().getParameter("ROLE_ID");
            HashSet parentIdSet = new HashSet();//存放已经存在了的MODULE_ID，用来在新加入节点时判断该节点的的父节点是否存在，以便决定时候显示该节点
            StringBuilder nodes = new StringBuilder();
            List sysList = sysSubSystemService.findListSubSystemForTree(ROLE_ID);
            for (int i = 0; i < sysList.size(); i++) {
                Map sysMap = (Map) sysList.get(i);
                //在SYSTEM_ID后添加9个0，使其变为MODULE_ID格式
                nodes.append(",{MODULE_ID:'").append(sysMap.get("SYSTEM_ID")).append("000000000',SYSTEM_ID:'").append(sysMap.get("SYSTEM_ID")).append("',name:'").append(sysMap.get("SYSTEM_NAME")).append("',checked:").append(sysMap.get("CHECKED")).append("}");
                parentIdSet.add(sysMap.get("SYSTEM_ID") + "000000000");
            }
            List<Map> moduleList = sysModuleService.findlModuleListForTree(ROLE_ID);
            for (int i = 0; i < moduleList.size(); i++) {
                Map<String, String> nodeMap = moduleList.get(i);
                if (parentIdSet.contains(nodeMap.get("PARENT_ID"))) {
                    nodes.append(",{MODULE_ID:'").append(nodeMap.get("MODULE_ID")).append("',PARENT_ID:'").append(nodeMap.get("PARENT_ID")).append("',name:'").append(nodeMap.get("MODULE_NAME")).append("',checked:").append(nodeMap.get("CHECKED")).append("}");
                    parentIdSet.add(nodeMap.get("MODULE_ID"));
                }
            }
            flag = "["+nodes.substring(1)+"]";
            return SUCCESS;
        }
        
	/**
	 * 显示查询模块列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String loadListModules() {
		String type = this.getRequest().getParameter("type");
		if(type!=null && type.equals("select"))
			return "SELECT";
		return SUCCESS;
	}
	public String loadListModulesManage() {
		return SUCCESS;
	}
	public String loadListModulesQueryJson() {
		HashMap map = new HashMap();
		map.put("PARENT_ID", theForm.getPARENT_ID());
		List mlst = null;
		if (theForm.getSEARCH_KEYWORD_NAME() != null && !theForm.getSEARCH_KEYWORD_NAME().trim().equals(""))
			map.put("MODULE_NAME", theForm.getSEARCH_KEYWORD_NAME().trim());
		
		IPage result = null;
		TblSYS_LOGINMSG user = this.getCurrentUser();
//		if(user.getLOGIN_ID().equalsIgnoreCase(CommUtil.USER_ADMIN))
			result = sysModuleService.findListByPK(map, this.getPageForm());
//		else{
//			map.put("LOGIN_ID", user.getLOGIN_ID());
//			result = sysModuleService.findListByPKLoginId(map, this.getPageForm());
//		}
		this.setResult(result);

		return SUCCESS;
	}

	/**
	 * 编辑模块列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String editModule() {
		String MODULE_ID = theForm.getMODULE_ID();
		if (theForm.getISMP_JSP_COMMAND() != null
				&& theForm.getISMP_JSP_COMMAND().equals("add")) {
			theForm.setMODULE_LAYOUT("2");
			return SUCCESS;

		}
		if (MODULE_ID != null && MODULE_ID != null) {

			TblSYS_MODULE obj = sysModuleService.findObjByPK(MODULE_ID);
			if (obj != null) {
				theForm.setMODULE_ID(obj.getMODULE_ID());
				theForm.setMODULE_NAME(obj.getMODULE_NAME());
				theForm
						.setMODULE_ENABLE(String
								.valueOf(obj.getMODULE_ENABLE()));
				theForm.setMODULE_PATH(obj.getMODULE_PATH());
				theForm.setModCode(obj.getMODULE_ID());
				theForm.setIS_REFRESH(obj.getIS_REFRESH());
				theForm.setIS_VIEW(obj.getIS_VIEW());
				theForm.setMODULE_LAYOUT(obj.getMODULE_LAYOUT());
				theForm.setOPEN_MODULE_ID(obj.getOPEN_MODULE_ID());
				theForm.setPAGE_ELEMENT(obj.getPAGE_ELEMENT());
				theForm.setVIEW_ORDER(obj.getVIEW_ORDER());
				theForm.setMODULE_TARGET(obj.getMODULE_TARGET());
				theForm.setSSO_TYPE(obj.getSSO_TYPE());
				if (theForm.getISMP_JSP_COMMAND().equals("copy")) {
					theForm.setModCode("");
				}
			}
		}

		return SUCCESS;
	}

	/**
	 * 保存
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String saveModule() {
		flag = "true";
		try{
			String modID = theForm.getMODULE_ID();// 改变的MODULE_ID
			if(modID==null||modID.equals("")){
				TblSYS_MODULE obj = new TblSYS_MODULE();
				obj.setMODULE_ID(RandomGUID.getRandomGUID());
				obj.setMODULE_ENABLE(Integer.parseInt(theForm.getMODULE_ENABLE()));
				obj.setMODULE_NAME(theForm.getMODULE_NAME());
				obj.setMODULE_PATH(theForm.getMODULE_PATH());
				obj.setIS_REFRESH(theForm.getIS_REFRESH());
				obj.setIS_VIEW(theForm.getIS_VIEW());
				obj.setMODULE_LAYOUT(theForm.getMODULE_LAYOUT());
				obj.setOPEN_MODULE_ID(theForm.getOPEN_MODULE_ID());
				obj.setPAGE_ELEMENT(theForm.getPAGE_ELEMENT());
				obj.setPARENT_ID(theForm.getPARENT_ID());
				obj.setVIEW_ORDER(theForm.getVIEW_ORDER());
				obj.setMODULE_TARGET(theForm.getMODULE_TARGET());
				if(!"0".equals(theForm.getPARENT_ID())){
					int module_level = Integer.parseInt(theForm.getMODULE_LEVEL()) + 1;
					obj.setMODULE_LEVEL(module_level);
				}
				obj.setSSO_TYPE(theForm.getSSO_TYPE());
				sysModuleService.add(obj);	
			}else{
				TblSYS_MODULE obj = sysModuleService.findObjByPK(modID);
				obj.setMODULE_ENABLE(Integer.parseInt(theForm.getMODULE_ENABLE()));
				obj.setMODULE_NAME(theForm.getMODULE_NAME());
				obj.setMODULE_PATH(theForm.getMODULE_PATH());
				obj.setIS_REFRESH(theForm.getIS_REFRESH());
				obj.setIS_VIEW(theForm.getIS_VIEW());
				obj.setMODULE_LAYOUT(theForm.getMODULE_LAYOUT());
				obj.setOPEN_MODULE_ID(theForm.getOPEN_MODULE_ID());
				obj.setPAGE_ELEMENT(theForm.getPAGE_ELEMENT());
				obj.setVIEW_ORDER(theForm.getVIEW_ORDER());
				obj.setMODULE_TARGET(theForm.getMODULE_TARGET());
				obj.setSSO_TYPE(theForm.getSSO_TYPE());
				
				sysModuleService.update(obj);
			}
			
			
			//计算模块显示层次
//			String tmpModuleParentId = modID.replaceAll("0(00)*$", "");
//			int module_level = tmpModuleParentId.length()/2;
			
		}catch(Exception e){
			e.printStackTrace();
			flag = e.getMessage();
		}
		return SUCCESS;
	}

	/**
	 * 删除模块
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	public String delModule() {
		flag = "true";
		String mIDs = theForm.getMODULE_ID();
		try {
			sysModuleService.deleteByPKs(mIDs);
			sysRoleModuleService.deleteByModIDS(mIDs);

		} catch (Exception e) {
			flag = e.getMessage();
		}

		return SUCCESS;
	}

	// modified by wangxyc 使模块与子系统对应
	public int getTypeLevel(String cModuleID) {
            /*
		int pos = cModuleID.indexOf("00");
		if (pos == -1)
			// return 5;
			return 0;
		else
			return (pos + 1) / 2;
             * */
            
            // 去除module_id末尾的奇数个零，比如cModuleID为 a100000000 去掉奇数个零后为a10 返回 "a10".length()/2 取整得 1
            //modified by liujhc 2011-4-27 10:50:35
            return cModuleID.replaceFirst("0(00)*$", "").length()/2;
	}

	public String getTypeParent(String cModuleID) {
		int level = 5;
		int pos = cModuleID.indexOf("00");
		if (pos == -1)
			level = 5;
		else
			level = (pos + 1) / 2;
		return cModuleID.substring(0, level * 2);
	}
        
        /**
         * 记录用户对模块的使用情况
         * <p>每次用户访问模块页面，就在日志表TB_SYS_USER_MODULE_LOG中插入一条记录</p>
         * @param mapping
         * @param form
         * @param request
         * @param response
         * @return
         * @throws Exception 
         */
        public String insertUserModuleLog() {
        	flag = "true";
    		try{
	            String MODULE_ID = this.getRequest().getParameter("MODULE_ID");
	            if (MODULE_ID != null) {
	                TblSYS_LOGINMSG userObj = this.getCurrentUser();
	                sysUserModuleLogService.insertUserModuleLog(MODULE_ID, userObj.getLOGIN_ID());
	            }
    		} catch (Exception e) {
    			flag = e.getMessage();
    		}
            return SUCCESS;
        }        
        
        public String showDetailReport() {
    		TblSYS_LOGINMSG curUser = this.getCurrentUser();
    		String login_id = curUser.getLOGIN_ID();
    		String super_module_id = this.getRequest().getParameter("module_id");
    		String pre_super = super_module_id.substring(0, super_module_id
    				.indexOf("00"));
    		moduleList = sysModuleService.getAllModuleForReport(login_id, pre_super,
    				pre_super.length());
    		return SUCCESS;
    	}
        
        public String intoRoleModuleRelationConfigPage(){
        	/*将Module分组，并返回json格式数据，一次性加载所有节点*/
        	return SUCCESS;
        }
        
        public String loadModuleInfoBySystemId(){
        	try{
        		String loginId = null;
//        		if(!this.getCurrentUser().getLOGIN_ID().equalsIgnoreCase(CommUtil.USER_ADMIN))
//        			loginId = this.getCurrentUser().getLOGIN_ID();
        		moduleList = sysModuleService.loadAllNodeLevelByParentId(loginId,systemId);
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        	return SUCCESS;
        }
        
        public String loadSystemNodeForJson(){
        	/*将Module分组，并返回json格式数据，一次性加载所有节点*/
        	try{
        		String loginId = null;
//        		if(!this.getCurrentUser().getLOGIN_ID().equalsIgnoreCase(CommUtil.USER_ADMIN))
//        			loginId = this.getCurrentUser().getLOGIN_ID();
        		//配置时不需要过滤权限
        		moduleList = sysModuleService.loadNextNodeLevelByParentId(loginId,systemId);
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        	return SUCCESS;
        }
        
        /**
         * 从模块树选择模块
         * @return
         */
        public String selectModuleTree(){
        	return SUCCESS;
        }

}